import tkinter as tk
from tkinter import messagebox

class GomokuGame:
    def __init__(self, master):
        self.master = master
        self.master.title("五子棋")
        self.master.geometry("600x650")
        self.master.resizable(False, False)
        
        # 确保中文显示正常
        self.master.option_add("*Font", "SimHei 10")
        
        # 游戏设置
        self.board_size = 15  # 15x15的棋盘
        self.cell_size = 40   # 每个格子的大小
        self.current_player = "black"  # 当前玩家：black或white
        self.game_over = False
        self.board = [[None for _ in range(self.board_size)] for _ in range(self.board_size)]
        
        # 创建UI
        self.create_ui()
    
    def create_ui(self):
        # 创建顶部信息栏
        info_frame = tk.Frame(self.master, bg="#f0f0f0", height=50)
        info_frame.pack(fill=tk.X)
        
        self.status_var = tk.StringVar(value="黑方回合")
        status_label = tk.Label(info_frame, textvariable=self.status_var, font=("SimHei", 16))
        status_label.pack(pady=10)
        
        # 创建棋盘
        canvas_frame = tk.Frame(self.master)
        canvas_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        self.canvas = tk.Canvas(
            canvas_frame,
            width=self.cell_size * self.board_size,
            height=self.cell_size * self.board_size,
            bg="#FFDEAD",  # 棋盘背景色（木色）
            highlightthickness=2,
            highlightbackground="#8B4513"  # 边框颜色
        )
        self.canvas.pack(fill=tk.BOTH, expand=True)
        
        # 绘制棋盘网格
        self.draw_board()
        
        # 绑定鼠标点击事件
        self.canvas.bind("<Button-1>", self.on_click)
        
        # 创建底部控制按钮
        control_frame = tk.Frame(self.master, bg="#f0f0f0", height=50)
        control_frame.pack(fill=tk.X)
        
        restart_button = tk.Button(
            control_frame,
            text="重新开始",
            command=self.restart_game,
            font=("SimHei", 12),
            bg="#4CAF50",
            fg="white",
            width=15
        )
        restart_button.pack(pady=10)
    
    def draw_board(self):
        """绘制棋盘网格"""
        # 清空画布
        self.canvas.delete("all")
        
        # 绘制网格线
        for i in range(self.board_size):
            # 水平线
            y = i * self.cell_size
            self.canvas.create_line(
                self.cell_size/2, y + self.cell_size/2,
                self.cell_size * (self.board_size - 0.5), y + self.cell_size/2,
                width=1
            )
            
            # 垂直线
            x = i * self.cell_size
            self.canvas.create_line(
                x + self.cell_size/2, self.cell_size/2,
                x + self.cell_size/2, self.cell_size * (self.board_size - 0.5),
                width=1
            )
        
        # 绘制天元和星位
        star_points = [(3, 3), (3, 11), (7, 7), (11, 3), (11, 11)]
        for x, y in star_points:
            self.canvas.create_oval(
                x * self.cell_size + self.cell_size/2 - 3,
                y * self.cell_size + self.cell_size/2 - 3,
                x * self.cell_size + self.cell_size/2 + 3,
                y * self.cell_size + self.cell_size/2 + 3,
                fill="black"
            )
        
        # 绘制已落子
        for i in range(self.board_size):
            for j in range(self.board_size):
                if self.board[i][j] is not None:
                    color = "black" if self.board[i][j] == "black" else "white"
                    self.draw_stone(i, j, color)
    
    def draw_stone(self, row, col, color):
        """在指定位置绘制棋子"""
        x = col * self.cell_size + self.cell_size/2
        y = row * self.cell_size + self.cell_size/2
        radius = self.cell_size/2 - 3
        
        # 绘制棋子
        self.canvas.create_oval(
            x - radius, y - radius,
            x + radius, y + radius,
            fill=color,
            outline="black" if color == "white" else ""
        )
    
    def on_click(self, event):
        """处理鼠标点击事件"""
        if self.game_over:
            return
        
        # 计算点击的格子位置
        col = int(event.x / self.cell_size)
        row = int(event.y / self.cell_size)
        
        # 检查位置是否合法
        if 0 <= row < self.board_size and 0 <= col < self.board_size:
            if self.board[row][col] is None:
                # 落子
                self.board[row][col] = self.current_player
                self.draw_stone(row, col, self.current_player)
                
                # 检查是否获胜
                if self.check_win(row, col):
                    winner = "黑方" if self.current_player == "black" else "白方"
                    self.status_var.set(f"{winner}获胜！")
                    self.game_over = True
                    messagebox.showinfo("游戏结束", f"{winner}获胜！")
                    return
                
                # 检查是否平局
                if self.check_tie():
                    self.status_var.set("平局！")
                    self.game_over = True
                    messagebox.showinfo("游戏结束", "平局！")
                    return
                
                # 切换玩家
                self.current_player = "white" if self.current_player == "black" else "black"
                self.status_var.set(f"{'黑方' if self.current_player == 'black' else '白方'}回合")
    
    def check_win(self, row, col):
        """检查当前玩家是否获胜"""
        directions = [
            (0, 1),   # 水平
            (1, 0),   # 垂直
            (1, 1),   # 对角线
            (1, -1)   # 反对角线
        ]
        
        player = self.board[row][col]
        
        for dx, dy in directions:
            count = 1  # 当前位置已经有一个棋子
            
            # 向正方向检查
            for i in range(1, 5):
                r = row + i * dx
                c = col + i * dy
                if 0 <= r < self.board_size and 0 <= c < self.board_size:
                    if self.board[r][c] == player:
                        count += 1
                    else:
                        break
                else:
                    break
            
            # 向反方向检查
            for i in range(1, 5):
                r = row - i * dx
                c = col - i * dy
                if 0 <= r < self.board_size and 0 <= c < self.board_size:
                    if self.board[r][c] == player:
                        count += 1
                    else:
                        break
                else:
                    break
            
            # 如果有5个连续的棋子，返回胜利
            if count >= 5:
                return True
        
        return False
    
    def check_tie(self):
        """检查是否平局"""
        for row in self.board:
            for cell in row:
                if cell is None:
                    return False
        return True
    
    def restart_game(self):
        """重新开始游戏"""
        self.board = [[None for _ in range(self.board_size)] for _ in range(self.board_size)]
        self.current_player = "black"
        self.game_over = False
        self.status_var.set("黑方回合")
        self.draw_board()

if __name__ == "__main__":
    root = tk.Tk()
    game = GomokuGame(root)
    root.mainloop()